<?php


namespace app\common\business;


class GoodsSku extends BusBass
{
    public $model = NUll;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\GoodsSku();
    }


    //多规格增逻辑
    public function saveAll($data)
    {
        //判断是否存在多规格
        if (!$data['skus']) {
            return false;
        }
        //组装数据
        foreach ($data['skus'] as $value) {
            $insertData[] = [
                "goods_id" => $data['goods_id'],
                "specs_value_id" => $value['propvalnames']['propvalids'],
                'price' => $value['propvalnames']['skuSellPrice'],
                'cost_price' => $value['propvalnames']['skuMarketPrice'],
                'stock' => $value['propvalnames']['skuStock']
            ];
        }
        //写入数据
        try {
            $result = $this->model->saveAll($insertData);
            return $result->toArray();
        } catch (\Exception $e) {
            //记录日志
            return false;
        }
        return true;
    }


    //获取正常的sku和goods数据 一对一关联查询
    public function getNormalSkuAndGoods($id)
    {
        //调用
        try {
            $result = $this->model->with("goods")->find($id);
        } catch (\Exception $e) {
            return [];
        }

        if (!$result) {
            return [];
        }
        $result = $result->toArray();

        if ($result['status'] != config("status.mysql.table_normal")) {
            return [];
        }

        return $result;

    }

    //通过goods_id 在sku表里查询sku数据
    public function getSkusByGoodsId($goodsId = 0)
    {
        if (!$goodsId) {
            return [];
        }

        try {
            $skus = $this->model->getNormalByGoodsId($goodsId);
        } catch (\Exception $e) {
            return [];
        }
        return $skus->toArray();
    }

    //根据id 获取SKU表数据 逻辑
    public function getNormalInIds($ids)
    {
        try {
            $result = $this->model->getNormalInIds($ids);
        } catch (\Exception $e) {
            return [];
        }

        return $result->toArray();
    }


    //库存修改
    public function updateStock($data)
    {
        //获取sku id
        $skuId = array_column($data, 'id');
        //获取库存
        $stock = (new \app\common\model\mysql\GoodsSku())->field("id,stock")->select($skuId);
        $stock = $stock->toArray();

        //当前商品数量
        $num = array_column($data, 'num');
        foreach ($stock as $k => $v) {
            $stock[$k]['stock'] = $stock[$k]['stock'] - $num[$k];
        }

        $res = $this->model->saveAll($stock);

        if (!$res) {
            return false;
        }
        return true;


    }

}